package com.yuanyi.changyihao.controller;

import com.yuanyi.changyihao.dao.TodoDao;
import com.yuanyi.changyihao.entity.Todo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;

@RestController
public class IndexController {

    @Autowired
    TodoDao todoDao;

    public static void main(String[] args) throws IOException {
        /**
         * 与网络进行交互（4行代码）
         */
        URL url = new URL("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=24_tlpYj0I--ehNerg_bnDz6XaJA99U_Y13Tv9ntve0EZcTSkXQoaQ9MLe4jMj6trwxbItJAjIMrj9xrKAUWJleXIgnC69-xxC5g6j7T_mQEEgGa1KzOhWMSTa2ZCoPTKnoTLLntnbvHoo_fdUeTZHhABABHP");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setDoInput(true);


        String sendStr = "{\"type\":\"voice\",\"offset\":0,\"count\":1}";
        con.getOutputStream().write(sendStr.getBytes());
        con.getOutputStream().flush();

        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        System.out.println(sb);

    }


    @PostMapping("/index")
    public String name(HttpServletRequest req) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), "utf-8"));
        String str;
        StringBuffer sb = new StringBuffer();
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        br.close();
        String xml = sb.toString();
        //xml 转 obj
        int start = xml.indexOf("CDATA[");
        int end = xml.indexOf("]", start);
        String toUserName = xml.substring(start + 6, end);

        start = xml.indexOf("CDATA[", end);
        end = xml.indexOf("]", start);
        String fromUserName = xml.substring(start + 6, end);

        Date date = new Date();
        String time = (date.getTime() / 1000 + "");

        start = xml.indexOf("MsgType", end);
        end = xml.indexOf("]", start);
        String msgType = xml.substring(start + 17, end);


        //String media_id = "8nDg_a3Njp1VMQG-WAnKQ1U79Ix2aoI1WxZes8tkYGI";

        if (msgType.equals("text")) {
            start = xml.indexOf("CDATA[", end);
            end = xml.indexOf("]", start);
            String msg = xml.substring(start + 6, end);
            return "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" +
                    "  <CreateTime>" + time + "</CreateTime>" +
                    "  <MsgType><![CDATA[text]]></MsgType>" +
                    "  <Content><![CDATA[" + msg + "]]></Content>" +
                    "</xml>";

        } else if (msgType.equals("image")) {
            start = xml.indexOf("MediaId", end);
            end = xml.indexOf("]", start);
            String media_id = xml.substring(start + 17, end);
            return "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>" +
                    "  <CreateTime>" + time + "</CreateTime>" +
                    "  <MsgType><![CDATA[image]]></MsgType>\n" +
                    "  <Image>\n" +
                    "    <MediaId><![CDATA[" + media_id + "]]></MediaId>\n" +
                    "  </Image>\n" +
                    "</xml>";
        } else if (msgType.equals("voice")) {
            start = xml.indexOf("CDATA[", end);
            end = xml.indexOf("]", start);
            String media_id = xml.substring(start + 6, end);
            return "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "  <CreateTime>" + time + "</CreateTime>\n" +
                    "  <MsgType><![CDATA[voice]]></MsgType>\n" +
                    "  <Voice>\n" +
                    "    <MediaId><![CDATA[" + media_id + "]]></MediaId>\n" +
                    "  </Voice>\n" +
                    "</xml>";

        } else if (msgType.equals("video")) {
            start = xml.indexOf("CDATA[", end);
            end = xml.indexOf("]", start);
            String media_id = xml.substring(start + 6, end);
            return "<xml>\n" +
                    "  <ToUserName><![CDATA[" + fromUserName + "]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA[" + toUserName + "]]></FromUserName>\n" +
                    "  <CreateTime>" + time + "</CreateTime>\n" +
                    "  <MsgType><![CDATA[video]]></MsgType>\n" +
                    "  <Video>\n" +
                    "    <MediaId><![CDATA[" + media_id + "]]></MediaId>\n" +
                    "    <Title><![CDATA[title]]></Title>\n" +
                    "    <Description><![CDATA[description]]></Description>\n" +
                    "  </Video>\n" +
                    "</xml>";
        } else {
            return "";
        }
    }

    @GetMapping("/index")
    public String name(String signature, String timestamp, String nonce, String echostr) {

        String[] strs = {"yihao", timestamp, nonce};
        Arrays.sort(strs);

        StringBuilder str = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            str.append(strs[i]);
        }

        MessageDigest md = null;
        String tempStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            tempStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        if (signature.toUpperCase().equals(tempStr)) {
            return echostr;
        }
        return "";
    }

    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private String byteToHexStr(byte b) {
        char[] digit = {
                '0',
                '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };
        char[] tempArr = new char[2];
        tempArr[0] = digit[(b >>> 4 & 0xF)];
        tempArr[1] = digit[b & 0xF];
        String s = new String(tempArr);
        return s;
    }

    @GetMapping(path = "/add") // Map ONLY POST Requests
    public String addNewUser(@RequestParam String name
            , @RequestParam String content) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        Todo t = new Todo();
        t.setContent(content);
        t.setCreatedate(new Date().toString());
        t.setName(name);

        todoDao.save(t);
        return "Saved";
    }

    @GetMapping(path = "/all")
    public @ResponseBody
    Iterable<Todo> getAllUsers() {
        return todoDao.findAll();
    }
}
